<?php

namespace app\mobile\controller;

use think\Db;
use think\Session;
use think\Controller;
use think\Request;
use think\Exception;
use app\interfaces\model\SignLog;
use app\mobile\model\MemberAddress;
use app\interfaces\model\DrawWinner;

class Draw extends Controller
{

    // protected $beforeActionList = [
    //     'checkLogin' => ['only' => 'index,ernie,notice,code,lottery_tips,prize_notes,goods'],
    //
    // ];


    // 抽奖主页
    public function index()
    {

        $user_id = Session::get('member_id');
        $giftList = Db::name('sign_info')->where(['status' => 1])->order('id', 'desc')->select();
        $restaraunts = array_column($giftList, 'title');
        $cover = array_column($giftList, 'cover');
        $color = array_column($giftList, 'color');
        $data = Db::name('draw_number')->where('id', $user_id)->find();


        return $this->fetch('', [
            'restaraunts' => json_encode($restaraunts),
            'cover'       => $cover,
            'color'       => json_encode($color),
            'times'       => $data['deal_time'] < date('Y-m-d') ? 3 : $data['number'],
            'total'       => Db::name('sign_log')->group('user_id')->count()
        ]);

    }

    public function rand_ss()
    {
        // 获取参数
        $user_id = Session::get('member_id');

        // 每次消耗积分
        $price = 1;

        $find = Db::name('member')->where('id', $user_id)->value('integral');

        if ($find < $price) {
            $data['status'] = '0';
            $data['rand'] = 0;
            $data['title'] = '您的积分不足!!';
            return json($data);
        }

        $giftList = Db::name('sign_info')->where(['status' => 1])->order('id', 'desc')->select();

        $total = Db::name('sign_info')->where(['status' => 1])->order('id', 'desc')->sum('inventory');
        Db::name('member')->where('id', $user_id)->setDec('integral', $price);
        $rand = 0;

        //概率数组的总概率精度
        //概率数组循环
        foreach ($giftList as $key => $value) {
            $randNum = mt_rand(1, $total);
            if ($randNum <= $value['inventory']) {
                $rand = $key;
                break;
            } else {
                $total -= $value['inventory'];
            }
        }

        if ($rand) {

            $data['status'] = 'y';
            $data['rand'] = $rand + 1;
            $data['title'] = '恭喜你获得：' . $giftList[$rand]['title'];

            $goods = Db::name('draw_goods')->where('id', $giftList[$rand]['good_id'])->find();

            if ($goods) {
                Db::name('draw_winner')->insert([
                    'member_id'   => $user_id,
                    'level'       => $rand + 1,
                    'goods_id'    => $giftList[$rand]['good_id'],
                    'picUrl'      => $goods['picUrl'],
                    'create_time' => time(),
                    'title'       => $goods['title'],
                ]);
                Db::name('sign_log')->insert([
                    'user_id'     => $user_id,
                    'gift_id'     => $giftList[$rand]['id'],
                    'create_time' => date('Y-m-d H:i:s', time())
                ]);
            }


        } else {
            $data['status'] = 'n';
            $data['title'] = '抽奖失败';
        }

        return json($data);

    }


    // 平台抽奖记录
    public function log(SignLog $log)
    {
        $data = $log->alias('a')->join('member u', 'a.user_id=u.id', 'left')
            ->join('sign_info g', 'a.gift_id=g.id', 'left')->select();

        return $this->fetch('log', [
            'data' => $data
        ]);
    }


    // 中奖记录
    public function order_list()
    {
        // 获取参数
        $user_id = Session::get('member_id');
        $status = Request::instance()->param('status', 0);

        if (empty($user_id)) throw new Exception('not empty');

        // 实例化
        $model = new DrawWinner();

        // 获取数据
        $ini = ['member_id' => $user_id, 'status' => $status];
        $data = $model->where($ini)->select();


        return $this->fetch('', [
            'mate_title' => '中奖记录',
            'data'       => $data
        ]);

    }


    // 记录详情
    public function order()
    {
        // 获取参数
        $order_id = Request::instance()->param('order_id');

        if (empty($order_id)) throw new Exception('not empty');

        $model = new DrawWinner();

        // 查询详情
        $item = $model->where('id', $order_id)->find();

        //用户默认收货地址
        $address = (new MemberAddress)->where(['member_id' => Session::get('member_id'), 'status' => 1])->field('id,name,phone,address,area_info')->find();


        return $this->fetch('', [
            'mate_title' => '抽奖记录详情',
            'item'       => $item,
            'address'    => $address,
        ]);
    }


    // 用户兑奖
    public function generating_order()
    {
        if (Request::instance()->isPost()) {
            // 获取数据
            $order_id = Request::instance()->param('order_id');
            $address_id = Request::instance()->param('address_id');

            // 获取收货地址
            $address = (new MemberAddress)->where('id',$address_id)->find();

            $model = new DrawWinner();

            // 生成数组
            $con = [
                'name'        => $address['name'],
                'phone'       => $address['phone'],
                'area_info'   => $address['area_info'],
                'address'     => $address['address'],
                'status'      => 1,
                'create_time' => date('Y-m-d', time()),
            ];

            // 操作
            $operation = $model->allowField(true)->save($con, ['id' => $order_id]);

            if ($operation) {
                return ['code' => 200, 'message' => '领取成功'];
            }
            return ['code' => 400, 'message' => 'Not Found'];
        }


    }


    // 确认收货
    public function confirmation()
    {
        // 获取参数
        $order_id = Request::instance()->param('order_id');

        if (empty($order_id)) throw new Exception('not Empty');

        // 实例化
        $model = new DrawWinner();

        // 操作
        $operation = $model->allowField(true)->save(['status' => 2], ['id' => $order_id]);

        if ($operation) {
            return ['code' => 200, 'message' => 'Ok'];
        }
        return ['code' => 400, 'message' => 'Not Found'];

    }


}